package game.module.user.logic;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import game.module.ddz.logic.DdzDataManager;
import game.module.mj.logic.MjDataManager;
import game.module.nn.logic.NnDataManager;
import game.module.qzmj.logic.QzmjDatamanager;
import game.module.sss.logic.SssDataManager;
import game.module.user.bean.PlayerBean;

public class RoomDataManager {

	private static Logger logger = LoggerFactory.getLogger(RoomDataManager.class);

	static class SingletonHolder {
		static RoomDataManager instance = new RoomDataManager();
	}

	public static RoomDataManager getInstance() {
		return SingletonHolder.instance;
	}

	private Cache<Integer, PlayerBean> playerCache = CacheBuilder.newBuilder().concurrencyLevel(8)
			.expireAfterAccess(3, TimeUnit.HOURS).build();

	public int getRoomType(int playerId) {
		int retRoomType = RoomConstants.ROOM_INVALID;
		if (DdzDataManager.getInstance().getDdzRoom(playerId) != null) {
			retRoomType = RoomConstants.ROOM_DDZ;
		} else if (NnDataManager.getInstance().getNnRoom(playerId) != null) {
			retRoomType = RoomConstants.ROOM_NN;
		} else if (SssDataManager.getInstance().getNnRoom(playerId) != null) {
			retRoomType = RoomConstants.ROOM_SSS;
		} else if (MjDataManager.getInstance().getMjRoom(playerId) != null) {
			retRoomType = RoomConstants.ROOM_MJ;
		}else if(QzmjDatamanager.getInstance().getMjRoom(playerId)!= null) {
			retRoomType = RoomConstants.ROOM_QZMJ;
		}
		return retRoomType;
	}

	public PlayerBean getPlayerBean(int playerId) {
		return playerCache.getIfPresent(playerId);
	}

	public void addOrUpdatePlayer(final int playerId, final String playerName, final int playerSex,
			final String headImg,long jindou) {
		try {
			PlayerBean pb = playerCache.get(playerId, new Callable<PlayerBean>() {
				@Override
				public PlayerBean call() throws Exception {
					PlayerBean pb = new PlayerBean();
					pb.setId(playerId);
					return pb;
				}
			});
			pb.setName(playerName);
			pb.setSex(playerSex);
			pb.setHeadimg(headImg);
			pb.setJindou(jindou);
		} catch (ExecutionException e) {
			logger.error("", e);
		}
	}

}
